package top.chukongxiang.monitorservice.tools.rtp;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ByteUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import java.nio.ByteOrder;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/11/3 17:37
 */
@Data
@RequiredArgsConstructor
public class PesWrapper {

    private final byte[] bytes;

    public int getDataLen() {
        return Short.toUnsignedInt(ByteUtil.bytesToShort(bytes, 4, ByteOrder.BIG_ENDIAN));
    }

    public boolean hasPts() {
        return ((byte) 0x80) == bytes[7] || ((byte) 0xC0) == bytes[7];
    }

    public boolean hasDts() {
        return ((byte) 0xC0) == bytes[7];
    }

    public int getHeaderLen() {
        return Byte.toUnsignedInt(bytes[8]);
    }

    private byte[] headerBytes = null;
    public byte[] getHeaderBytes() {
        if (headerBytes != null) {
            return headerBytes;
        }
        int headerLen = getHeaderLen();
        headerBytes = ArrayUtil.sub(bytes, 9, 9 + headerLen);
        return headerBytes;
    }

    private byte[] payload = null;
    public byte[] getPayload() {
        if (payload != null) {
            return payload;
        }
        int dataLen = getDataLen();
        int headerLen = getHeaderLen();
        payload = ArrayUtil.sub(bytes, 9 + headerLen, 6 + dataLen);
        return payload;
    }

}
